/*
 * ModulesInstantiator.java July 2009
 *
 * Copyright (C) 2009, Quirino Zagarese <quirino@laszloitalia.org>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General
 * Public License along with this library; if not, write to the
 * Free Software Foundation, Inc., 59 Temple Place, Suite 330,
 * Boston, MA  02111-1307  USA
 */
package org.eu4ria.core;

import java.util.Hashtable;
import java.util.Properties;

import javassist.CtClass;
import javassist.NotFoundException;
import javassist.bytecode.AnnotationsAttribute;
import javassist.bytecode.annotation.Annotation;

import javax.naming.InitialContext;
import javax.naming.NamingException;

public class ModulesInstantiator {

	private Hashtable<String, Object> objects = new Hashtable<String, Object>();

	private InitialContext context;

	public ModulesInstantiator() {

		try {
			context = new InitialContext();
		} catch (NamingException e) {
			System.err
					.println("Can not initialize naming with default params.");
			e.printStackTrace();
		}
	}

	public ModulesInstantiator(Properties jndiProperties) {

		try {
			context = new InitialContext(jndiProperties);
		} catch (NamingException e) {
			System.err
					.println("Can not initialize naming with provided params. Please check your jndi.properties file.");
			e.printStackTrace();
		}
	}

	public Object getInstanceOf(CtClass class1) throws ClassNotFoundException {
		Object object = objects.get(class1.getName());
		if (object == null) {
			if (isEJB(class1)) {
				try {
					object = loadAsEJB(class1);
				} catch (NotFoundException e) {
					throw new ClassNotFoundException();
				}
			} else {
				try {
					object = Class.forName(class1.getName(),true, EU4RIAClassLoader.getInstance()).newInstance();
				} catch (InstantiationException e) {
					System.err
							.println("Can not instantiate class "
									+ object.getClass().getName()
									+ ". \nPlease make sure it provides a visible default constructor.");
					e.printStackTrace();
				} catch (IllegalAccessException e) {
					System.err
							.println("Can not access class"
									+ object.getClass().getName()
									+ ". \nPlease make sure it provides a visible constructor with no params.");
					e.printStackTrace();
				}
			}
			objects.put(class1.getName(), object);

		}
		return object;
	}

	private boolean isEJB(CtClass class1) throws ClassNotFoundException {
		return isStateful(class1) || isStateless(class1)
				|| isMessageDriven(class1);
	}

	private Object loadAsEJB(CtClass class1) throws NotFoundException {
		CtClass[] interfaces = class1.getInterfaces();
		Object object = null;
		for (CtClass c : interfaces) {
			if (c.isInterface()) {
				if (isLocal(c)) {
					try {
						object = context.lookup(class1.getSimpleName()
								+ "/local");
					} catch (NamingException e) {
						System.err
								.println("Can not find the EJB component named "
										+ object.getClass().getSimpleName()
										+ "/local. \nPlease check your jndi.properties file.");
						e.printStackTrace();
					}
				} else if (isRemote(c)) {
					try {
						object = context.lookup(class1.getSimpleName()
								+ "/remote");
					} catch (NamingException e) {
						System.err
						.println("Can not find the EJB component named "
								+ object.getClass().getSimpleName()
								+ "/remote. \nPlease check your jndi.properties file.");
						e.printStackTrace();
					}
				}
			}
		}

		return object;

	}

	private boolean isStateless(CtClass c) {
		AnnotationsAttribute attr = (AnnotationsAttribute) c.getClassFile()
				.getAttribute(AnnotationsAttribute.visibleTag);
		if (attr == null) {
			return false;
		}
		Annotation annotation = attr.getAnnotation("javax.ejb.Stateless");
		return (annotation != null);
	}

	private boolean isStateful(CtClass c) {
		AnnotationsAttribute attr = (AnnotationsAttribute) c.getClassFile()
				.getAttribute(AnnotationsAttribute.visibleTag);
		if (attr == null) {
			return false;
		}
		Annotation annotation = attr.getAnnotation("javax.ejb.Stateful");
		return (annotation != null);
	}

	private boolean isMessageDriven(CtClass c) {
		AnnotationsAttribute attr = (AnnotationsAttribute) c.getClassFile()
				.getAttribute(AnnotationsAttribute.visibleTag);
		if (attr == null) {
			return false;
		}
		Annotation annotation = attr.getAnnotation("javax.ejb.MessageDriven");
		return (annotation != null);
	}

	private boolean isRemote(CtClass c) {
		AnnotationsAttribute attr = (AnnotationsAttribute) c.getClassFile()
				.getAttribute(AnnotationsAttribute.visibleTag);
		if (attr == null) {
			return false;
		}
		Annotation annotation = attr.getAnnotation("javax.ejb.Remote");
		return (annotation != null);
	}

	private boolean isLocal(CtClass c) {
		AnnotationsAttribute attr = (AnnotationsAttribute) c.getClassFile()
				.getAttribute(AnnotationsAttribute.visibleTag);
		if (attr == null) {
			return false;
		}
		Annotation annotation = attr.getAnnotation("javax.ejb.Local");
		return (annotation != null);
	}

}
